/**
 * WebSocket管理
 */
class WebSocketManager {
	public constructor() {
	}

	private static _instance:WebSocketManager;
	public static instance():WebSocketManager{
		if(!WebSocketManager._instance){
			WebSocketManager._instance = new WebSocketManager();
		}
		return WebSocketManager._instance;
	}


	private _socket:egret.WebSocket;

	public init(){
		if(!this._socket){
			this._socket = new egret.WebSocket();
			this._socket.type = egret.WebSocket.TYPE_BINARY;
			this._socket.addEventListener(egret.ProgressEvent.SOCKET_DATA, this.onReceiveMessage, this);
			this._socket.addEventListener(egret.Event.CONNECT, this.onSocketOpen, this);
			this._socket.addEventListener(egret.Event.CLOSE, this.onSocketClose, this);
			this._socket.addEventListener(egret.IOErrorEvent.IO_ERROR, this.onSocketError, this);
		}
	}

	private onReceiveMessage(e:egret.ProgressEvent){
        let byte:egret.ByteArray = new egret.ByteArray();
		byte.endian = egret.Endian.LITTLE_ENDIAN;
        this._socket.readBytes(byte);

		let encodedString = String.fromCharCode.apply(null, byte.bytes);
		let data = JSON.parse(encodedString);

		LogUtil.log('---接收服务器数据---');
		LogUtil.log(data);

	}

	private onSocketOpen(e:egret.Event){
		LogUtil.log('---连接服务器成功---');
	}

	private onSocketClose(e:egret.Event){
		LogUtil.log('---服务器断开连接---');
	}

	private onSocketError(e:egret.IOErrorEvent){
		LogUtil.log(e);
	}

	/**
	 * 连接服务器
	 */
	public connect(){
		if(!this._socket.connected){
			this._socket.connectByUrl('ws://ws.xiaowanyou.com:9005/websocket.php');
		}
	}

	/**
	 * 发送数据
	 */
	public send(byte:egret.ByteArray){
		byte.position = 0;
		if(this._socket){
			this._socket.writeBytes(byte, 0, byte.bytesAvailable);
			this._socket.flush();
		}
	}
}